package com.toppitch.site.feed;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.toppitch.site.data.NYTNewsItem;

@Lazy(false)
@Component
public class RssThread extends Thread {

	private static final String URL = "http://dealbook.nytimes.com/category/main-topics/hedge-funds/feed/";

	private Vector<NYTNewsItem> items = new Vector<NYTNewsItem>();

	public RssThread() {
		setDaemon(true);
		this.start();
	}

	public void run() {
		while (true) {
			try {
				HttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(URL);
				HttpResponse response = null;
				InputStream is = null;
				try {
					response = httpClient.execute(httpGet);
					HttpEntity entity = response.getEntity();
					if (entity != null) {
						is = entity.getContent();
					}
					NYTNewsSaxHandler sh = new NYTNewsSaxHandler();
					SAXParserFactory.newInstance().newSAXParser().parse(is, sh);
					synchronized (items) {
						items.removeAllElements();
						items.addAll(sh.getNewsItems());
					}
				} catch (Throwable e) {
					e.printStackTrace();
				} finally {
					if (is != null) {
						try {
							is.close();
						} catch (IOException e) {
						}
					}
					httpClient.getConnectionManager().shutdown();
				}
			} catch (Throwable e) {
				e.printStackTrace();
			}
			try {
				sleep(60 * 60000);
			} catch (InterruptedException e) {
			}
		}
	}

	public Vector<NYTNewsItem> getItems() {
		return items;
	}
}
